// ------主函数------
let board = new Array()
let score = 0
let hasConflicted = new Array()

// $(document).ready(function () {
//     newgame()
//     alert('1111')
// })

let startx = 0
let starty = 0
let endx = 0
let endy = 0

$(function () {
    prepareForMobile()
    newgame()

})
function prepareForMobile() {

    if (documentWidth > 500) {
        gridContainerWidth = 500
        cellSpace = 20
        cellSideLength = 100
    }
    $('#grid-container').css('width', gridContainerWidth - 2 * cellSpace)
    $('#grid-container').css('height', gridContainerWidth - 2 * cellSpace)
    $('#grid-container').css('padding', cellSpace)
    $('#grid-container').css('border-radius', 0.02 * gridContainerWidth)

    $('.grid-cell').css('width', cellSideLength)
    $('.grid-cell').css('height', cellSideLength)
    $('.grid-cell').css('border-radius', 0.02 * cellSideLength)
}
function newgame() {
    //初始化棋盘
    init()
    // //初始化分数
    // score = 0
    //随机2个格子上升生成数字
    generateOneNumber()
    generateOneNumber()

}

function init() {
    for (let i = 0; i < 4; i++) {
        for (let j = 0; j < 4; j++) {
            let gridCell = $(`#grid-cell-${i}-${j}`)
            gridCell.css('top', getPosTop(i, j))
            gridCell.css('left', getPosLeft(i, j))
        }
    }
    //board数组
    for (let i = 0; i < 4; i++) {
        //二维数组
        board[i] = new Array()
        hasConflicted[i] = new Array()
        for (let j = 0; j < 4; j++) {
            //初始化小格子
            board[i][j] = 0;
            hasConflicted[i][j] = false
        }
    }
    updateBoardView();

    score = 0
    $('#score').text(score)
}
// 通知前端根据board来改变
function updateBoardView() {
    //添加number-cell
    $(".number-cell").remove();
    for (let i = 0; i < 4; i++) {
        for (let j = 0; j < 4; j++) {
            $("#grid-container").append(`<div class="number-cell" id="number-cell-${i}-${j}"></div>`)
            let theNumberCell = $(`#number-cell-${i}-${j}`);

            //数字块样式设置
            if (board[i][j] == 0) {
                theNumberCell.css('width', '0px');
                theNumberCell.css('height', '0px');
                theNumberCell.css('top', getPosTop(i, j) + cellSideLength / 2);
                theNumberCell.css('left', getPosLeft(i, j) + cellSideLength / 2);
            } else {
                theNumberCell.css('width', cellSideLength);
                theNumberCell.css('hegiht', cellSideLength);
                theNumberCell.css('top', getPosTop(i, j));
                theNumberCell.css('left', getPosLeft(i, j));
                //NumberCell覆盖
                theNumberCell.css('background-color', getNumberBackgroundColor(board[i][j]));//返回背景色
                theNumberCell.css('color', getNumberColor(board[i][j]));
                theNumberCell.text(board[i][j]);
            }
            hasConflicted[i][j] = false
        }
    }
    $('.number-cell').css('line-height', `${cellSideLength}px`)
    $('.number-cell').css('font-size', `${0.6 * cellSideLength}px`)
}

//生成函数
function generateOneNumber() {
    if (nospace(board)) {
        return false
    }
    //随机一个位置
    let randx = parseInt(Math.floor(Math.random() * 4))
    let randy = parseInt(Math.floor(Math.random() * 4))
    let times = 0
    while (true < 50) {
        if (board[randx][randy] == 0) {
            break;
        }
        randx = parseInt(Math.floor(Math.random() * 4))
        randy = parseInt(Math.floor(Math.random() * 4))
        times++
    }
    if (times == 50) {
        for (let i = 0; i < 4; i++) {
            for (let j = 0; j < 4; j++) {
                if (board[i][j] = 0) {
                    randx = i
                    randy = j
                }
            }
        }
    }

    //随机一个数字
    let randNumber = Math.random() < 0.5 ? 2 : 4
    //在随机位置显示随机数字
    board[randx][randy] = randNumber
    showNumberWithAnimation(randx, randy, randNumber)
    return true
}
$(document).keydown(function (event) {
    event.preventDefault()
    switch (event.keyCode) {
        case 37:
            // console.log(111)
            if (moveLeft()) {
                setTimeout("generateOneNumber()", 210)
                setTimeout("isgameover()", 300)
            }
            break;
        case 38:
            if (moveUp()) {
                setTimeout("generateOneNumber()", 210)
                setTimeout("isgameover()", 300)
            }
            break;
        case 39:
            if (moveRight()) {
                setTimeout("generateOneNumber()", 210)
                setTimeout("isgameover()", 300)
            }
            break;
        case 40:
            if (moveDown()) {
                setTimeout("generateOneNumber()", 210)
                setTimeout("isgameover()", 300)
            }
            break;

        default:
            break;
    }
})
//触控
document.addEventListener('touchstart', function (event) {
    startx = event.touches[0].pageX
    starty = event.touches[0].pageY
})
document.addEventListener('touchend', function (event) {
    endx = event.changedTouches[0].pageX
    endy = event.changedTouches[0].pageY

    //方向判断
    let deltax = endx - startx
    let deltay = endy - starty
    //判断点击
    if(Math.abs(deltax)<0.3*documentWidth&&Math.abs(deltay)<0.3*documentWidth){
        return
    }
    //x
    if (Math.abs(deltax) >= Math.abs(deltay)) {
        if (deltax > 0) {
            //向右
            if (moveRight()) {
                setTimeout("generateOneNumber()", 210)
                setTimeout("isgameover()", 300)
            }
        } else {
            //向左
            if (moveLeft()) {
                setTimeout("generateOneNumber()", 210)
                setTimeout("isgameover()", 300)
            }
        }
    }
    //y
    else {
        if (deltay > 0) {
            //向下
            if (moveDown()) {
                setTimeout("generateOneNumber()", 210)
                setTimeout("isgameover()", 300)
            }
        } else {
            //向上
            if (moveUp()) {
                setTimeout("generateOneNumber()", 210)
                setTimeout("isgameover()", 300)
            }
        }
    }

})

function isgameover() {
    if (nospace(board) && nomove(board)) {
        gameover()
    }
}
function gameover() {
    alert("Game Over!")
}
//左
function moveLeft() {
    //能否向左移动
    if (!canMoveLeft(board)) {
        return false
    }
    //向左移动
    for (let i = 0; i < 4; i++) {
        for (let j = 1; j < 4; j++) {
            //移动到的位置
            if (board[i][j] != 0) {
                //board[i][j]所有左边的元素board[i][k]
                for (let k = 0; k < j; k++) {
                    //移动落脚点
                    if (board[i][k] == 0 && noBlockHorizontal(i, k, j, board)) {
                        //move
                        showMoveAnimation(i, j, i, k)
                        board[i][k] = board[i][j]
                        board[i][j] = 0
                        continue
                    }
                    //移动的落脚点和移动的元素数字相等
                    else if (board[i][k] == board[i][j] && noBlockHorizontal(i, k, j, board) && !hasConflicted[i][k]) {
                        //move
                        showMoveAnimation(i, j, i, k)
                        //叠加
                        board[i][k] += board[i][j]
                        board[i][j] = 0
                        //加分
                        score += board[i][k]
                        updatedScore(score)
                        hasConflicted[i][k] = true
                        continue
                    }
                }
            }
        }
    }
    setTimeout("updateBoardView()", 200);
    return true
}
//右
function moveRight() {
    //判断
    if (!canMoveRight(board)) {
        return false
    }
    //移动
    for (let i = 0; i < 4; i++) {
        for (let j = 2; j >= 0; j--) {
            if (board[i][j] != 0) {
                for (let k = 3; k > j; k--) {
                    if (board[i][k] == 0 && noBlockHorizontal(i, j, k, board)) {
                        showMoveAnimation(i, j, i, k)
                        board[i][k] = board[i][j]
                        board[i][j] = 0
                        continue
                    }
                    //叠加
                    else if (board[i][k] == board[i][j] && noBlockHorizontal(i, j, k, board) && !hasConflicted[i][k]) {
                        showMoveAnimation(i, j, i, k)
                        board[i][k] *= 2
                        board[i][j] = 0
                        //加分
                        score += board[i][k]
                        updatedScore(score)

                        hasConflicted[i][k] = true
                        continue
                    }
                }
            }

        }
    }
    setTimeout("updateBoardView()", 200);
    return true
}
//上
function moveUp() {
    //判断
    if (!canMoveUp(board)) {
        return false
    }
    //移动
    for (let j = 0; j < 4; j++) {
        for (let i = 1; i < 4; i++) {
            if (board[i][j] != 0) {
                for (let k = 0; k < i; k++) {
                    if (board[k][j] == 0 && noBlockVertical(j, k, i, board)) {
                        showMoveAnimation(i, j, k, j)
                        board[k][j] = board[i][j]
                        board[i][j] = 0
                        continue
                    }
                    else if (board[k][j] == board[i][j] && noBlockVertical(j, k, i, board) && !hasConflicted[k][j]) {
                        showMoveAnimation(i, j, k, j)
                        board[k][j] *= 2
                        board[i][j] = 0
                        //加分
                        score += board[k][j]
                        updatedScore(score)
                        hasConflicted[k][j] = true
                        continue
                    }
                }
            }
        }
    }
    setTimeout("updateBoardView()", 200)
    return true
}
//下
function moveDown() {
    if (!canMoveDown(board)) {
        return false
    }
    for (let j = 0; j < 4; j++) {
        for (let i = 2; i >= 0; i--) {
            if (board[i][j] != 0) {
                for (let k = 3; k > i; k--) {
                    if (board[k][j] == 0 && noBlockVertical(j, i, k, board)) {
                        showMoveAnimation(i, j, k, j)
                        board[k][j] = board[i][j]
                        board[i][j] = 0
                        continue
                    }
                    else if (board[k][j] == board[i][j] && noBlockVertical(j, i, k, board) && !hasConflicted[k][j]) {
                        showMoveAnimation(i, j, k, j)
                        board[k][j] *= 2
                        board[i][j] = 0
                        //加分
                        score += board[k][j]
                        updatedScore(score)

                        hasConflicted[k][j] = true
                        continue
                    }
                }
            }
        }
    }
    setTimeout("updateBoardView()", 200)
    return true
}